package com.railway.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.railway.bean.Carriage;
import com.railway.bean.Page;
import com.railway.bean.Pass;
import com.railway.bean.Seat;
import com.railway.bean.Train;
import com.railway.dao.TrainDao;
import com.railway.dao.impl.TrainDaoImpl;
import com.railway.service.TrainService;

public class TrainServiceImpl implements TrainService {

	TrainDao td = new TrainDaoImpl();
	
	@Override
	public List<Train> selectOneWayTrains(Map<String,String[]> map) {
		Set<String> keys = map.keySet(); //取出条件中所有的键
		String start ;
		String terminal ;
		
		for (String key : keys) {
			if("start".equals(key) && !"".equals(map.get(key)[0])) {
				start = map.get(key)[0];
				for (String key2 : keys) {
					if("terminal".equals(key2) && !"".equals(map.get(key2)[0])) {
						for (String key3 : keys) {
							if("date".equals(key3) && !"".equals(map.get(key3)[0])) {
								terminal = map.get(key2)[0];
								String date = map.get(key3)[0];
								List<Train> li = selectTrains(start,terminal,getDate(date));
								if(li != null && li.size()>0) {
									for (Train tr : li) {
										if(tr.getIs_exist()==0) {//筛选停运的车
											tr = null;
										}
									}
								}
								return li;
							}
						}
					}
				}
				
			}
		}
		return null;
	}
	
	public List<Train> selectTrains(String start ,String terminal,List<Date> date){
		List<Integer> start_id;
		List<Integer> terminal_id;
		List<Integer> train_id = new ArrayList();
		List<Train> li = new ArrayList();
		start = start.trim();
		terminal = terminal.trim();
		start_id = td.selectStation(start);
		terminal_id = td.selectStation(terminal);
		if(start_id.size()> 0 && terminal_id.size()>0) {
			for (int i = 0; i < start_id.size(); i++) {
				for (int j = 0; j < start_id.size(); j++) {
					List<Train> a = td.selectTrainIdByStation(start_id.get(i), terminal_id.get(j),date);//查询列车
					for (Train train : a) {
						train_id.add(train.getTrain_id());
					}
					for (Integer t : train_id) {
						if(td.selectTranById(t).get(0) != null) {
							Train train = td.selectTranById(t).get(0);//检索列车
							train.setStart_station(td.selectStationById(start_id.get(i)));//列车中添加出发站id
							train.setTerminal_station(td.selectStationById(terminal_id.get(j)));//添加到达站id
							train.setStart_pass_id(td.selectPass_id(start_id.get(i), t));//添加途径第一个站的id
							train.setTerminal_pass_id(td.selectPass_id(terminal_id.get(j), t));//添加途径最后一个站的id
							li.add(train);
						}
					}
					if(li != null) {
						li = addCarriage(li);
						li = addPass(li);
						return li;
					}
				}
			}
			
		}
		return null;
		
	}
	
	public List<Train> selectTwoWayTrains(Map<String,String[]> map) {
		Set<String> keys = map.keySet(); //取出条件中所有的键
		String start ;
		String terminal ;
		List<List<Train>> twotrain = new ArrayList();
		
		for (String key : keys) {
			if("start".equals(key) && !"".equals(map.get(key)[0])) {
				for (String key2 : keys) {
					if("terminal".equals(key) && !"".equals(map.get(key2)[0])) {
						for (String key3 : keys) {
							if("date".equals(key) && !"".equals(map.get(key3)[0])) {
								start = map.get(key)[0];
								terminal = map.get(key2)[0];
								String date = map.get(key3)[0];
								List<Train> temp= selectTrains(start,terminal,getDate(date));
								twotrain.add(temp);
							}
						}
						
						for (String key3 : keys) {
							if("date2".equals(key) && !"".equals(map.get(key3)[0])) {
								start = map.get(key2)[0];
								terminal = map.get(key)[0];
								String date2 = map.get(key3)[0];
								List<Train> temp= selectTrains(start,terminal,getDate(date2));
								twotrain.add(temp);
							}
						}
					}
				}
				
			}
		}
		return null;
	}	

	public List<Train> addCarriage(List<Train> li){
		List<Carriage> camage;
		for (Train train : li) {
			if(train != null) {
				camage = td.selectCarriage(train.getTrain_id());	
				if(camage != null) {
					train.setCamage(camage);
				}
			}
		}
		return li;
	}
	
	public List<Train> addPass(List<Train> li){
		for (Train train : li) {
			if(train != null) {
				if(td.selectPass(train.getTrain_id()) != null) {
					List<Pass> pass = td.selectPass(train.getTrain_id());
					train.setPass(pass);//给已经查询到的列车添加途径的站
				}
			}
		}
		return li;
	}
	
	public List<Date> getDate(String date){
		Date nowtime = new Date();//获取现在的时间
		List<Date> li = new ArrayList<Date>();
		
		DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
		String currentDate = dft.format(nowtime);//获取今日的日期
		Date currentDateStartTime = null;
		dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			currentDateStartTime = dft.parse(currentDate+" 00:00:00");//获取今日的凌晨时间yyyy-MM-dd00:00:00
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Date ultimateTime = new Date((currentDateStartTime.getTime())+(1000*60*60*24*4));//获取5天后的凌晨时间
		
		currentDate +=" 23:59:59";
		Date currentDateFinishTime = null;
		try {
			currentDateFinishTime = dft.parse(currentDate);//今天结束时间23：59：59
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		Date ultimateFinishTime = new Date((currentDateFinishTime.getTime())+(1000*60*60*24*4));//获取5天后的结束时间
		
		dft = new SimpleDateFormat("yyyy-MM-dd");
		Date expectTime = null;//预期出发日期的凌晨时间
		try {
			expectTime = dft.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		date +=" 23:59:59";
		Date expectFnishTime = null;//预计出发的日期的结束时间
		dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			expectFnishTime = dft.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(currentDateStartTime.getTime()>expectTime.getTime()) {//如果选择日期在今天之前，返回查询时间在现在到今天结束
			li.add(0, nowtime);
			li.add(1, currentDateFinishTime);
			return li;
		}else if(currentDateStartTime.getTime() == expectTime.getTime()) {//如果选择日期在今天，返回查询时间在现在到今天结束
			li.add(0,nowtime);
			li.add(1,currentDateFinishTime);
			return li;
		}else if(currentDateStartTime.getTime() < expectTime.getTime() && expectTime.getTime() <= ultimateTime.getTime()) {
			li.add(0,nowtime);
			li.add(1,expectFnishTime);
			return li;
		}else if(expectTime.getTime() > ultimateTime.getTime()) {
			return null;
		}
		return null;
	}

	@Override
	public int addTrain(Map<String,String[]> map) {
		int train_id = td.selectTrainCount()+1;
		String train_name = "";//车次
		int train_type = 0;//车类型
		int train_size = 0;//车长
		int camagetemp = 1;//临时变量
		int camage_type = 1;//车厢类型
		String[] pass_station = null;//经过的车站
		Double[] next_distance = null;
		
		int principaSeat_num = 1;//贵宾车厢
		int firstSeat_num = 2;//一等车厢
		int secondSeat_num = 6;//二等车厢
		
		Set<String> keys = map.keySet();
		
		for (String key : keys) {
			if("train_name".equals(key) && !"".equals(map.get(key)[0])) {
				train_name = map.get(key)[0];
			}
			
			if("train_type".equals(key) && !"".equals(map.get(key)[0])) {
				train_type = Integer.parseInt(map.get(key)[0]);
			}
			
			if("train_size".equals(key) && !"".equals(map.get(key)[0])) {
				train_size = Integer.parseInt(map.get(key)[0]);
			}
			
			if("pass_station".equals(key) && map.get(key) != null) {
				pass_station = map.get(key);
			}
		}
		

		
		int temp = setTrain(train_id, train_name, train_type, pass_station, train_size);
		if(temp > 0) {
			temp = setPass(train_id, pass_station, next_distance);
			if(temp >0 ) {
				temp = addCarriage(train_id, train_size, principaSeat_num, firstSeat_num, secondSeat_num);
				if(temp == 0) {
					delete(train_id);
					return 0;
				}
			}else {
				delete(train_id);
				return 0;
			}
		}else {
			delete(train_id);
			return 0;
		}
		return 1;
	}
	
	public int setSeat(int train_id,int seat_type,int camagetemp) {
		int temp = 0;
		String[] ch = {"A","B","C","D","F"};
		if(seat_type == 1) {
			for (int i = 1; i <= 10; i++) {
				for (int j = 1; j <= ch.length; j++) {
				}
			}
		}
		return temp;
	}
	
	public int setCarriage(int train_id,int carriage_num,int carriage_type) {
		Carriage carriage = new Carriage(train_id,carriage_num,carriage_type);
		return td.insertCarriage(carriage);
	}
	
	public int setPass(int train_id,String[] pass_station,Double[] next_distance) {
		int temp = 0;
		for (int i = 0; i < pass_station.length; i++) {
			int station_id = td.selectStation_id(pass_station[i]);
			
			Pass pass = new Pass((i+1),train_id,station_id,(i+1),next_distance[i]);
			temp = td.insertPass(pass);
		}
		return temp;
	}
	
	/**添加列车
	 * @param train_id
	 * @param train_name
	 * @param train_type
	 * @param pass_station
	 * @param pass_time
	 * @param count_distance
	 * @return
	 */
	public int  setTrain(int train_id,String train_name,int train_type,
			String[] pass_station, double count_distance) {
		

		int start_station_id = 0;
		int terminal_station_id = 0;
		start_station_id = td.selectStation_id(pass_station[0]);
		terminal_station_id = td.selectStation_id(pass_station[pass_station.length-1]);
		
		Train train = new Train(train_id, train_name, train_type, start_station_id, 
				terminal_station_id, null, null, count_distance);
		return td.insertTrain(train);
	}
	
	/**添加车厢和座位
	 * @param train_id
	 * @param train_size
	 * @param principaSeat_num
	 * @param firstSeat_num
	 * @param secondSeat_num
	 * @return
	 */
	public int addCarriage(int train_id,int train_size,int principaSeat_num,int firstSeat_num,int secondSeat_num){
		int temp = 0;
		int camagetemp = 0;
		int temp2 = 0;
			for (int i = 0; i < train_size; i++) {
				if(principaSeat_num >0) {
					temp = setCarriage(train_id,camagetemp,1);
					if(temp == 1) {
						if(temp2 == 1) {
							principaSeat_num--;
							camagetemp++;
						}
					}
				}else if(firstSeat_num > 0) {
					if(principaSeat_num >0) {
						if(temp == 1) {
							temp2 = setSeat(train_id,2,camagetemp);
							if(temp2 == 1) {
								firstSeat_num--;
								camagetemp++;
							}
						}
				}else if(secondSeat_num >0) {
					if(principaSeat_num >0) {
						temp = setCarriage(train_id,camagetemp,3);
						if(temp == 1) {
							temp2 = setSeat(train_id,3,camagetemp);
							if(temp2 == 1) {
								secondSeat_num--;
								camagetemp++;
							}
						}
					
					}
				}
			}
		}
		if(temp == 0) {
			return 0;
		}
		
		if(temp2 == 0) {
			return 0;
		}
		return 1;
	}
	
	/**用于删除列车
	 * @param train_id
	 */
	public void delete(int train_id) {
		td.deleteTrain(train_id);
		td.deletePass(train_id);
		td.deleteCarriage(train_id);
		td.deleteSeat(train_id);
	}

	@Override
	public Page<Train> selectTrain(int pageNum, int pageSize) {
		List<Train> data = td.selectTrainAll(pageNum, pageSize);
		for (Train train : data) {
			if(train != null) {
				if(td.selectPass(train.getTrain_id()) != null) {
					train.setPass(td.selectPass(train.getTrain_id()));
				}
				
				if(td.selectStationById(train.getStarting_station_id()) != null) {
					train.setStart_station(td.selectStationById(train.getStarting_station_id()));
				}
				
				if(td.selectStationById(train.getTerminal_station_id()) != null) {
					train.setTerminal_station(td.selectStationById(train.getTerminal_station_id()));
				}
			}
			
		}
		int totalRows = td.selectTrainCount();
		Page<Train> page = new Page(data,pageNum,pageSize,totalRows);
		return page;
	}

	@Override
	public int settrainTime(int train_id, String[] pass_time, String[] stading_time) {
		String starting_time = "";
		String terminal_time = "";
		for (int i = 0; i < pass_time.length; i++) {
			if(i == 0) {
				starting_time = (String)pass_time[i];//给发车时间赋值
			}else if(i == pass_time.length-1) {
				terminal_time = (String)pass_time[pass_time.length-1];//给终点站赋值
			}
			td.insertPassTime(train_id, (String)pass_time[i], Integer.parseInt((String) stading_time[i]));//添加此途径站时间
		}
		return td.insertTrainTime(train_id, starting_time, terminal_time);//添加列车发车和到达时间
	}
}
